package com.qilin.hammer;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import com.vitria.fc.xpath.XPathException;
import com.vitria.xquery.XQueryLib;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import junit.framework.TestCase;

public class XQueryTest extends TestCase {

	private static final Log log_ = LogFactory.getLog(XQueryTest.class);
	private Integer threshold = 0;
	private static DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
	
	public void testGetFirstFromXPath() throws Exception{
		int threadNum = 1000;
		int loops = 1;
		final Element ele;
		DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
		String runtimeinfo = "<runtime-info><servers>"
            +"<server id=\"srv1\" type=\"runtimeServer\" value=\"DefaultPool/\" label=\"Runtime server\"/>"
            +"<server id=\"feedSrv1\" type=\"feedServer\" value=\"automatic\" label=\"Feed server\"/>"
            +"</servers><datasources>"
            +"<datasource id=\"ds1\" value=\"automatic\" label=\"Data source\"/></datasources>"
            +"</runtime-info>";
		InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(runtimeinfo));

		Document dom = domBuilder.parse(is);
		ele = dom.getDocumentElement();
    	for(int i=0; i < loops+1; i++){
    		synchronized(threshold){
    			if(threshold == 0){
    				if(i == loops)
    					break;
    				threshold = threadNum;
    				System.out.println("Loop:"+(i+1));
    			} else {
    				//Thread.sleep(1000);
    				i--;
    				continue;
    			}
    		}
    		for(int j=0; j<threadNum; j++){
    			new Thread(){
    				public void run(){
    					try {
    						
    						String serverId = "srv1";
    						String dsValue = null;
    				    	if(ele != null) {
    				    		try {
    				    			Object v = XQueryLib.getFirstFromXPath(ele, "servers/server[@id='" + serverId + "']/@value");
    				    			if(v instanceof Attr){
    				    				dsValue = ((Attr)v).getValue();
    				    				System.out.println(dsValue);
    				    			}
    				    		} catch (XPathException e) {
    				    			log_.error("error");
    				    		}
    				    	}
				    		synchronized(threshold){
				    			threshold--;
				    		}
						} catch (Exception e) {
							e.printStackTrace();
						}
    				}
    			}.start();
    		}
    	}
	}
	
}
